package com.yijian.oj.judge.codesandbox.strategy.impl;

import cn.hutool.json.JSONUtil;
import com.yijian.oj.judge.codesandbox.model.JudgeContext;
import com.yijian.oj.judge.codesandbox.strategy.JudgeStrategy;
import com.yijian.oj.model.dto.question.JudgeCase;
import com.yijian.oj.model.dto.question.JudgeConfig;
import com.yijian.oj.judge.codesandbox.model.JudgeInfo;
import com.yijian.oj.model.entity.Question;
import com.yijian.oj.model.enums.JudgeInfoMessageEnum;

import java.util.List;

/**
 * 默认判题策略
 * @author ItJianGe
 * @data 2024/3/25 11:46
 */
public class DefaultJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        judgeInfo.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());

        // 判断沙箱输出的结果与预期数量是否一致
        if (inputList.size() != outputList.size()) {
            judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
            return judgeInfo;
        }

        // 依次判断结果是否一致
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if (!judgeCase.getOutput().equals(outputList.get(i))) {
                judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
                return judgeInfo;
            }
        }

        // 校验题目配置是否合规
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        // 判断是否超过规定时间
        Long time = judgeInfo.getTime();
        Long timeLimit = judgeConfig.getTimeLimit();
        if (time > timeLimit) {
            judgeInfo.setMessage(JudgeInfoMessageEnum.TIME_LIMIT.getValue());
            return judgeInfo;
        }
        // 判断是否超过内存空间
        Long memory = judgeInfo.getMemory();
        Long memoryLimit = judgeConfig.getMemoryLimit();
        if (memory > memoryLimit) {
            judgeInfo.setMessage(JudgeInfoMessageEnum.MEMORY_LIMIT.getValue());
            return judgeInfo;
        }
        return judgeInfo;
    }
}
